<?php
// 应用公共文件

use app\common\service\AuthService;
use think\facade\Cache;

if (!function_exists('__url')) {

    /**
     * 构建URL地址
     * @param string $url
     * @param array $vars
     * @param bool $suffix
     * @param bool $domain
     * @return string
     */
    function __url(string $url = '', array $vars = [], $suffix = true, $domain = false)
    {
        return url($url, $vars, $suffix, $domain)->build();
    }
}

if (!function_exists('password')) {

    /**
     * 密码加密算法
     * @param $value 需要加密的值
     * @param $type  加密类型，默认为md5 （md5, hash）
     * @return mixed
     */
    function password($value)
    {
        $value = sha1('blog_') . md5($value) . md5('_encrypt') . sha1($value);
        return sha1($value);
    }

}

if (!function_exists('xdebug')) {

    /**
     * debug调试
     * @param string|array $data 打印信息
     * @param string $type 类型
     * @param string $suffix 文件后缀名
     * @param bool $force
     * @param null $file
     */
    function xdebug($data, $type = 'xdebug', $suffix = null, $force = false, $file = null)
    {
        !is_dir(runtime_path() . 'xdebug/') && mkdir(runtime_path() . 'xdebug/');
        if (is_null($file)) {
            $file = is_null($suffix) ? runtime_path() . 'xdebug/' . date('Ymd') . '.txt' : runtime_path() . 'xdebug/' . date('Ymd') . "_{$suffix}" . '.txt';
        }
        file_put_contents($file, "[" . date('Y-m-d H:i:s') . "] " . "========================= {$type} ===========================" . PHP_EOL, FILE_APPEND);
        $str = (is_string($data) ? $data : (is_array($data) || is_object($data)) ? print_r($data, true) : var_export($data, true)) . PHP_EOL;
        $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
    }
}

if (!function_exists('sysconfig')) {

    /**
     * 获取系统配置信息
     * @param $group
     * @param null $name
     * @return array|mixed
     */
    function sysconfig($group, $name = null)
    {
        $where = ['group' => $group];
        $value = empty($name) ? Cache::get("sysconfig_{$group}") : Cache::get("sysconfig_{$group}_{$name}");
        if (empty($value)) {
            if (!empty($name)) {
                $where['name'] = $name;
                $value = \app\admin\model\SystemConfig::where($where)->value('value');
                Cache::tag('sysconfig')->set("sysconfig_{$group}_{$name}", $value, 3600);
            } else {
                $value = \app\admin\model\SystemConfig::where($where)->column('value', 'name');
                Cache::tag('sysconfig')->set("sysconfig_{$group}", $value, 3600);
            }
        }
        return $value;
    }
}

if (!function_exists('array_format_key')) {

    /**
     * 二位数组重新组合数据
     * @param $array
     * @param $key
     * @return array
     */
    function array_format_key($array, $key)
    {
        $newArray = [];
        foreach ($array as $vo) {
            $newArray[$vo[$key]] = $vo;
        }
        return $newArray;
    }

}

if (!function_exists('auth')) {

    /**
     * auth权限验证
     * @param $node
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function auth($node = null)
    {
        $authService = new AuthService(session('admin.id'));
        $check = $authService->checkNode($node);
        return $check;
    }

}


/**
 * debug json
 *
 * @param array $var
 * @throws Exception
 */
function _dj($var)
{


    if(is_array($var)){

//        array(
//            'param_list' => ( new ReflectionMethod(__CLASS__, __FUNCTION__) )->getParameters(),
//            'value_list' => func_get_args(),
//            'num' => func_num_args(),
//        );

        header('Content-Type', 'application/json;');
        echo json_encode($var, 255);die;
    }

    throw new Exception('data type is must array.');
}

/**
 * 实例化Model
 *
 * @param string $table
 * @return \app\common\model\BaseModel
 */
function model($table = '')
{
    return new \app\common\model\BaseModel($table);
}

/**
 * 框架自带 生成树状数据结构
 *
 * @param $pid
 * @param $list
 * @param int $level
 * @return array
 */
function buildPidMenu($pid, $list, $level = 0)
{
    $newList = [];
    foreach ($list as $vo) {
        if ($vo['pid'] == $pid) {
            $level++;
            foreach ($newList as $v) {
                if ($vo['pid'] == $v['pid'] && isset($v['level'])) {
                    $level = $v['level'];
                    break;
                }
            }
            $vo['level'] = $level;
            if ($level > 1) {
                $repeatString = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                $markString   = str_repeat("{$repeatString}├{$repeatString}", $level - 1);
                $vo['title']  = $markString . $vo['title'];
            }
            $newList[] = $vo;
            $childList = buildPidMenu($vo['id'], $list, $level);
            !empty($childList) && $newList = array_merge($newList, $childList);
        }

    }

    return $newList;
}

/**
 * 平面数据 生成 树状结构 (下级关系链)
 *
 * @param $data
 * @param string $p_key
 * @return array
 */
function createTree(&$data, $p_key='parent_id')
{

    $tree = array();
    foreach($data as $key => $value){

        $p_val = $value[$p_key];
        //如果pid这个节点存在
        if(isset($data[$p_val])){
            //把当前的$value放到pid节点的son中
            $data[$p_val]['children'][] = &$data[$key];
        }else{
            $tree[] = &$data[$key];
        }
    }

    return $tree;
}

/**
 * 树状数据结构 解构
 *
 * @param $tree
 * @param int $level
 * @param string $p_key_prefix
 * @param array $result
 * @return array
 */
function parseTree($tree, $level=1, $p_key_prefix='p_id', &$result=array())
{

    foreach($tree as $key => $info){

        $result[$p_key_prefix . ($level)][] = $info;
        if(!empty($info['children'])){
            parseTree($info['children'], ++$level, $p_key_prefix, $result);
        }
    }

    return $result;
}

/**
 * 写入txt文件log
 * @param  string $name 文件名
 * @param  string|array $data 数据
 */
function write_log($name,$data){
    !is_array($data) ?: $data = json_encode($data, 256);
    file_put_contents(
        '../runtime/log/'.$name.date('Y-m-d').'.txt',
        '时间:' . date('Y-m-d H:i:s') . PHP_EOL .
        '数据:'.($data). PHP_EOL . PHP_EOL . PHP_EOL,
        FILE_APPEND
    );
}

/**
 * 获取 最后执行sql
 *
 * @return string
 */
function lastSql()
{

    return \think\facade\Db::name('')->getLastSql();
}

/**
 * api json return
 *
 * @param int $code
 * @param string $msg
 * @param array $data
 */
function _return($code=0, $msg='', $data=array())
{

    $result = [
        'timestamp' => time(),
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ];
    exit(json_encode($result, 256));
}

/**
 * 获取 ip地址
 *
 * @return array|false|mixed|string
 */
function getIp() {
    $real_ip = '';
    if (isset($_SERVER)) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $real_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $real_ip = $_SERVER['HTTP_CLIENT_IP'];
        } else {
            $real_ip = $_SERVER['REMOTE_ADDR'];
        }
    } else {
        if (getenv('HTTP_X_FORWARDED_FOR')) {
            $real_ip = getenv('HTTP_X_FORWARDED_FOR');
        } else if (getenv('HTTP_CLIENT_IP')) {
            $real_ip = getenv('HTTP_CLIENT_IP');
        } else {
            $real_ip = getenv('REMOTE_ADDR');
        }
    }
    return $real_ip;
}